<?php
namespace Apps\Back\Controllers;
use Apps\Back\Controllers\ControllerAuth;
use Apps\Model\Pay;
use Apps\Model\User;
use Apps\Model\Userbalance;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;

class PayController extends ControllerAuth{

  //查询所有订单和按状态查询订单

   public function indexAction($currentPage=1,$state=0,$tel=''){
        $condition=array();
   	    if($this->request->isPost()){
   	    	$state=$this->request->getPost('state','int');
   	    	$tel=$this->request->getPost('tel','string');
   	    }
   	    if($state>0) 
   	    		$condition[]="state=".$state;
   	    if($tel){
	   	    	$user=User::findFirst("tel=".$tel);
	   	    	$user_id=$user->id;
	   	    	$condition[]="user_id='".$user_id."'";
   	    }
   	    $row= Pay::find(array(
   	    	implode(' and ', $condition),
   	    	'order'=>'id asc'
   	    	)); 
       //数据分页
   	    $paginator   = new PaginatorModel(
          array(
              "data"  => $row,
              "limit" => 5,
              "page"  => $currentPage
          )
        );
       
        $page = $paginator->getPaginate();
	    $this->view->setVar('page',$page);
	    $this->view->setVar('state',$state);
	    $this->view->setVar('tel',$tel);
   }

  
    public function successAction($id,$currentPage,$state,$tel=''){
    	 $this->view->disable();
    	//运用事务
         $manager     = $this->di->getTransactions();
         $transaction = $manager->get();

         //根据pay数据表的id修改state 
         $map= pay::findFirst("id=".$id);
         $map->setTransaction($transaction);
         $map -> state = 2;

         //根据用户表的id充值金额
         $user = User::findFirst("id=".$map->user_id);
         $user-> money += $map-> money;
         $balance=new Userbalance();
         $balance->user_id=$user->id;
         $balance->flag=1;
         $balance->addtime=time();
         $balance->money=$map->money;
         $balance->admin_id=$this->_operator->id;  
         if($user -> save() == false || $map -> save() == false || $balance->save() ==  false){
         	$transaction->rollback("操作失败");
         }

         $transaction->commit();
         //跳转到前一个页面
         $this->response->redirect("admin/pay/index/$currentPage/$state/$tel");
    }

    public function delAction($id,$currentPage,$state,$tel=''){
      	$row=pay::findFirst("id=".$id);
  	    $row->delete();
        $this->response->redirect("admin/pay/index/$currentPage/$state/$tel");
    }

    public function delallAction($currentPage,$state,$tel=''){
        $this->view->disable();
        $ids=$this->request->getPost('ids','int');
        foreach($ids as $id){
          $row=pay::find("id='$id'");
          $row->delete(); 
      }
        $this->response->redirect("admin/pay/index/$currentPage/$state/$tel");
    }
 }